const createError = require('http-errors');
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const cors = require('cors');
const session = require('express-session')
const { secret } = require('./config/global')

// 导入路由
const backendRouter = require('./routes/backend');
const frontRouter = require('./routes/front');


const app = express();

// 注册express-session中间件
app.use(session({
  secret,
  resave: false,
  saveUninitialized: true,
  // secure：设置为true， 获取不到之前写入的session
  cookie: { secure: false }
}))

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
// 注册中间件
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());

// 注册跨域请求中间件
app.use(cors());

// 托管静态资源
app.use(express.static(path.join(__dirname, 'public')));
app.use('/uploads', express.static(path.join(__dirname, 'uploads')));

// 注册路由
// 后台管理系统数据接口路由
app.use('/api', backendRouter);

// 前台数据接口
app.use('/c', frontRouter);


// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  // res.render('error');
  res.send({
    code: 500,
    msg: "error"
  });
});

module.exports = app;
